package com.ajavaer.framework.web.advice;

import com.ajavaer.framework.common.message.Message;
import com.ajavaer.framework.common.tools.JsonTools;
import com.ajavaer.framework.common.validate.ValidationException;
import com.ajavaer.framework.config.AjavaerConfig;
import com.ajavaer.framework.core.web.controller.BaseController;
import com.ajavaer.framework.exception.LoginTimeOutException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.annotation.Resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@ControllerAdvice
public class CMSExceptionAdvice extends BaseController {
    Logger log = LoggerFactory.getLogger(CMSExceptionAdvice.class);

    @Resource
    private Environment env;
    @Resource
    private AjavaerConfig serverConfig;

    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    }

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Message errorHandler(Exception ex) {
        if (ex instanceof LoginTimeOutException) {
            return Message.fail(HttpStatus.FORBIDDEN, "登录信息失效,请重新登录");
        }
        if (ex instanceof UnauthorizedException) {
            return Message.fail(HttpStatus.FORBIDDEN, "权限不足:" + ex.getMessage());
        }
        if (ex instanceof AuthorizationException) {
            return Message.fail(HttpStatus.FORBIDDEN, "权限不足:" + ex.getMessage());
        }
        if (ex instanceof ValidationException) {
            return Message.fail(((ValidationException) ex).getValidationResult().getMsg());
        }
        if (ex instanceof MethodArgumentTypeMismatchException) {
            String param = "";
            if (ex.getMessage() != null) {
                Pattern p = Pattern.compile("\\{(.){1,}\\}");
                Matcher matcher = p.matcher(ex.getMessage());
                if (matcher.find()) {
                    param = matcher.group();
                }
            }
            return Message.fail("请求参数错误:" + param);
        }
        String message = "系统内部错误";
        StringBuilder error = new StringBuilder();
        error.append("env:").append(JsonTools.beanToJson(env.getActiveProfiles())).append(ex.getMessage());
        log.error(error.toString(), ex);

        if (serverConfig.getDebug()) {
            message = error.toString();
        }
        return Message.fail(HttpStatus.INTERNAL_SERVER_ERROR, message);
    }
}
